<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
	const DAY=86400;
	const HORA=3600;
		protected function isAuthorize(){
    $loginStatus=session('loginStatus');
    if($loginStatus){
      $this->userId=session('userId');
      $this->userName=session('user_name');
      $this->assign('userName',$this->userName);
      $this->assign('userId',$this->userId); 
	  return true;
     }
      return false;
   }
	
    public function index(){
		$this->isAuthorize();
		$this->display();
    }
	
	public function selectCar(){
		$this->isAuthorize();
		$ordersObj=D('orders');
		$carObj=D('Car');
		$diffTime=intval($_GET['endData'])-intval($_GET['startData']);
		$day=intval($diffTime/(self::DAY));
		$hora=intval($diffTime%(self::DAY)/self::HORA);
		$totalDay=$diffTime/(self::DAY);
		$ordersList=$ordersObj->getBusydCar(intval($_GET['startData']),intval($_GET['endData']));
		$carIdList='';
		foreach($ordersList as $value){
			$carIdList.=$value['car_id'].',';
		}
		$carIdList=rtrim($carIdList,',');

		$freeCarLisr=$carObj->getFreeCarList($carIdList);
		$this->assign('carList',$freeCarLisr);
		$this->assign('startData',intval($_GET['startData']));
		$this->assign('endData',intval($_GET['endData']));
		$this->assign('day',$day);
		$this->assign('hora',$hora);
		$this->assign('totalDay',$totalDay);
		$this->display('selectCar');
	}
	
	public function reserveCar($carId,$startData,$endData){
		if(!$this->isAuthorize()){
			$this->gotoNote('登陆后才能订车',"/index.php/Home/Manager/userLogin");
			return false;
		}
		$startData=intval($startData);
		$endData=intval($endData);
		$ordersObj=D('orders');
		$status=$ordersObj->isBusyCar($carId,$startData,$endData);
		if($status===null){
			$ordersId=$ordersObj->reserveCar($this->userId,$carId,$startData,$endData);
			if($ordersId){
				$this->gotoNote('预定成功',"/index.php/Home/user/");
			}else{
				$this->gotoNote('数据库发生错误',"/index.php/Home/Index/selectCar?startData/$startData/endData/$endData");
			}
		}
		if($status){
			$this->gotoNote('车辆已经被预定了，重新选择',"/index.php/Home/Index/selectCar?startData/$startData/endData/$endData");
			return false;
		}
		if($status=== false){
			$this->gotoNote('数据库发生错误',"/index.php/Home/Index/selectCar?startData/$startData/endData/$endData");
		}
		
	}
	
		 public function gotoNote($noteString,$url){
		 $this->assign('noteString',$noteString);
		 $this->assign('url',$url);
		 $this->display('Note/note');
	 }
	public function liuYan(){
		$this->display('liuYan');
	}
	
}